package com.uniontech.template.util;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;

public class Tools {

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 生成自定长度的随机字符串
     *
     * @param length 随机字符串总长度
     * @return 随机字符串
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return randomStr(str, length);
    }

    /**
     * 生成自定长度的随机大写字符串
     *
     * @param length 随机字符串总长度
     * @return 随机字符串
     */
    public static String getRandomUpperString(int length) {
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return randomStr(str, length);
    }

    /**
     * 生成自定长度的随机小写字符串
     *
     * @param length 随机字符串总长度
     * @return 随机字符串
     */
    public static String getRandomLowerString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyz0123456789";
        return randomStr(str, length);
    }

    /**
     * 生成自定长度的数字字符串
     *
     * @param length
     * @return
     */
    public static String getRandomNum(int length) {
        String str = "0123456789";
        return randomStr(str, length);
    }

    private static String randomStr(String sedStr, int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(sedStr.length());
            sb.append(sedStr.charAt(number));
        }
        return sb.toString();
    }


    public static <T> void txtToObject(String text, T t) {
        Assert.notNull(text, "text must not be null");
        Assert.notNull(t, "t must not be null");
        T tnew = (T) JSONObject.parseObject(text, t.getClass());
        copyPropertiesIgnoreNull(tnew, t);
    }

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * @param source 源对象
     * @param target 目标对象
     * @Description <p>
     * 拷贝非空对象属性值
     * </P>
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }
}
